<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>维修论坛 - 家电维修系统</title>
    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/css/all.min.css}" rel="stylesheet">
    <link th:href="@{/css/quill.snow.min.css}" rel="stylesheet">
    <style>
        .forum-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .post-card {
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            transition: transform 0.2s;
        }
        .post-card:hover {
            transform: translateY(-2px);
        }
        .post-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px;
            border-bottom: 1px solid #eee;
        }
        .post-meta {
            color: #6c757d;
            font-size: 0.9rem;
        }
        .post-content {
            padding: 15px;
        }
        .comment-section {
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #dee2e6;
        }
        .comment {
            margin-bottom: 15px;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 5px;
        }
        .comment-meta {
            font-size: 0.85rem;
            color: #6c757d;
            margin-bottom: 5px;
        }
        .reply-section {
            margin-left: 20px;
            margin-top: 10px;
        }
        #editor {
            height: 200px;
            margin-bottom: 20px;
        }
        .user-info {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
        }
        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin-right: 10px;
        }
        .nav-tabs {
            margin-bottom: 20px;
        }
        .post-stats {
            display: flex;
            gap: 15px;
            color: #6c757d;
            font-size: 0.9rem;
        }
        .post-stats i {
            margin-right: 5px;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="#">家电维修系统</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link active" href="#">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/orders">我的订单</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/profile">个人资料</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/announcements">公告</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/forum">论坛</a>
                    </li>
                </ul>
                <div class="d-flex">
                    <span class="navbar-text me-3" id="userInfo"></span>
                    <button class="btn btn-outline-light" onclick="logout()">退出</button>
                </div>
            </div>
        </div>
    </nav>

    <div class="forum-container">
        <!-- 发帖按钮 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>维修论坛</h2>
            <button class="btn btn-primary" onclick="showPostModal()">
                <i class="fas fa-plus me-2"></i>发布帖子
            </button>
        </div>

        <!-- 帖子列表 -->
        <div id="posts-container">
            <!-- 帖子将通过JavaScript动态加载 -->
        </div>

        <!-- 分页控件 -->
        <nav aria-label="Page navigation" class="mt-4">
            <ul class="pagination justify-content-center" id="pagination">
            </ul>
        </nav>
    </div>

    <!-- 发帖模态框 -->
    <div class="modal fade" id="postModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">发布帖子</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="postForm">
                        <div class="mb-3">
                            <label for="title" class="form-label">标题</label>
                            <input type="text" class="form-control" id="title" required>
                        </div>
                        <div class="mb-3">
                            <label for="content" class="form-label">内容</label>
                            <div id="editor"></div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="submitPost()">发布</button>
                </div>
            </div>
        </div>
    </div>

    <script th:src="@{/js/jquery.min.js}"></script>
    <script th:src="@{/js/bootstrap.bundle.min.js}"></script>
    <script th:src="@{/js/quill.min.js}"></script>
    <script>
        let quill;
        let postModal;
        let currentPage = 1;

        $(document).ready(function() {
            // 初始化富文本编辑器
            quill = new Quill('#editor', {
                theme: 'snow',
                modules: {
                    toolbar: [
                        ['bold', 'italic', 'underline', 'strike'],
                        ['blockquote', 'code-block'],
                        [{ 'header': 1 }, { 'header': 2 }],
                        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                        [{ 'script': 'sub'}, { 'script': 'super' }],
                        [{ 'indent': '-1'}, { 'indent': '+1' }],
                        [{ 'direction': 'rtl' }],
                        [{ 'size': ['small', false, 'large', 'huge'] }],
                        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                        [{ 'color': [] }, { 'background': [] }],
                        [{ 'font': [] }],
                        [{ 'align': [] }],
                        ['clean'],
                        ['link', 'image']
                    ]
                }
            });

            // 初始化模态框
            postModal = new bootstrap.Modal(document.getElementById('postModal'));

            // 检查是否已登录
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = '/login';
                return;
            }

            // 加载用户信息
            loadUserInfo();

            // 加载帖子列表
            loadPosts();
        });

        function loadUserInfo() {
            $.ajax({
                url: '/api/user/info',
                type: 'GET',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                success: function(user) {
                    $('#username').text(user.username);
                    $('#userType').text(user.userType === 1 ? '用户' : '维修工');
                },
                error: function(xhr) {
                    if (xhr.status === 401) {
                        window.location.href = '/login';
                    }
                }
            });
        }

        function showPostModal() {
            $('#postForm')[0].reset();
            quill.root.innerHTML = '';
            postModal.show();
        }

        function submitPost() {
            const title = $('#title').val();
            const content = quill.root.innerHTML;

            if (!title || !content) {
                alert('请填写完整内容');
                return;
            }

            $.ajax({
                url: '/api/forum/posts',
                type: 'POST',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                contentType: 'application/json',
                data: JSON.stringify({
                    title: title,
                    content: content
                }),
                success: function() {
                    postModal.hide();
                    loadPosts(1);
                    alert('发布成功');
                },
                error: function(xhr) {
                    if (xhr.status === 401) {
                        window.location.href = '/login';
                    } else {
                        alert('发布失败');
                    }
                }
            });
        }

        function loadPosts(page = 1) {
            currentPage = page;
            $.ajax({
                url: '/api/forum/posts',
                type: 'GET',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                data: {
                    page: page,
                    size: 10
                },
                success: function(response) {
                    const container = $('#posts-container');
                    container.empty();

                    response.posts.forEach(post => {
                        container.append(`
                            <div class="card post-card">
                                <div class="post-header">
                                    <h5 class="card-title mb-0">${post.title}</h5>
                                    <div class="post-meta">
                                        <span>${post.username}</span> |
                                        <span>${new Date(post.createTime).toLocaleString()}</span>
                                    </div>
                                </div>
                                <div class="post-content">
                                    <div class="card-text">${post.content}</div>
                                </div>
                                
                                <div class="comment-section">
                                    <h6>评论</h6>
                                    <div class="comments-list" id="comments-${post.id}">
                                        <!-- 评论将通过JavaScript动态加载 -->
                                    </div>
                                    <div class="mt-3">
                                        <textarea class="form-control" rows="2" 
                                            placeholder="写下你的评论..." id="comment-${post.id}"></textarea>
                                        <button class="btn btn-primary btn-sm mt-2" 
                                            onclick="submitComment(${post.id})">发表评论</button>
                                    </div>
                                </div>
                            </div>
                        `);
                        loadComments(post.id);
                    });

                    updatePagination(response.total, page);
                },
                error: function(xhr) {
                    if (xhr.status === 401) {
                        window.location.href = '/login';
                    }
                }
            });
        }

        function loadComments(postId) {
            $.ajax({
                url: `/api/forum/posts/${postId}/comments`,
                type: 'GET',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                success: function(comments) {
                    const container = $(`#comments-${postId}`);
                    container.empty();

                    comments.forEach(comment => {
                        container.append(`
                            <div class="comment">
                                <div class="comment-meta">
                                    <span>${comment.realName || comment.username}</span> | 
                                    <span>${new Date(comment.createTime).toLocaleString()}</span>
                                </div>
                                <div class="comment-content">${comment.content}</div>
                                <div class="mt-2">
                                    <button class="btn btn-link btn-sm p-0" 
                                        onclick="showReplyForm(${postId}, ${comment.id})">
                                        回复
                                    </button>
                                </div>
                                <div class="reply-section" id="reply-${comment.id}"></div>
                            </div>
                        `);
                        loadReplies(comment.id);
                    });
                }
            });
        }

        function loadReplies(parentId) {
            $.ajax({
                url: `/api/forum/comments/${parentId}/replies`,
                type: 'GET',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                success: function(replies) {
                    const container = $(`#reply-${parentId}`);
                    container.empty();

                    replies.forEach(reply => {
                        container.append(`
                            <div class="comment">
                                <div class="comment-meta">
                                    <span>${reply.realName || reply.username}</span> | 
                                    <span>${new Date(reply.createTime).toLocaleString()}</span>
                                </div>
                                <div class="comment-content">${reply.content}</div>
                            </div>
                        `);
                    });
                }
            });
        }

        function submitComment(postId) {
            const content = $(`#comment-${postId}`).val();
            if (!content) {
                alert('请输入评论内容');
                return;
            }

            $.ajax({
                url: '/api/forum/comments',
                type: 'POST',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                contentType: 'application/json',
                data: JSON.stringify({
                    postId: postId,
                    content: content
                }),
                success: function() {
                    $(`#comment-${postId}`).val('');
                    loadComments(postId);
                },
                error: function(xhr) {
                    if (xhr.status === 401) {
                        window.location.href = '/login';
                    } else {
                        alert('评论失败');
                    }
                }
            });
        }

        function showReplyForm(postId, parentId) {
            const container = $(`#reply-${parentId}`);
            container.prepend(`
                <div class="mt-2">
                    <textarea class="form-control" rows="2" 
                        placeholder="回复 ${parentId}" id="reply-content-${parentId}"></textarea>
                    <button class="btn btn-primary btn-sm mt-2" 
                        onclick="submitReply(${postId}, ${parentId})">回复</button>
                </div>
            `);
        }

        function submitReply(postId, parentId) {
            const content = $(`#reply-content-${parentId}`).val();
            if (!content) {
                alert('请输入回复内容');
                return;
            }

            $.ajax({
                url: '/api/forum/comments',
                type: 'POST',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                contentType: 'application/json',
                data: JSON.stringify({
                    postId: postId,
                    content: content,
                    parentId: parentId
                }),
                success: function() {
                    $(`#reply-content-${parentId}`).val('');
                    loadReplies(parentId);
                },
                error: function(xhr) {
                    if (xhr.status === 401) {
                        window.location.href = '/login';
                    } else {
                        alert('回复失败');
                    }
                }
            });
        }

        function updatePagination(total, currentPage) {
            const totalPages = Math.ceil(total / 10);
            const pagination = $('#pagination');
            pagination.empty();

            // 上一页
            pagination.append(`
                <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="loadPosts(${currentPage - 1})">上一页</a>
                </li>
            `);

            // 页码
            for (let i = 1; i <= totalPages; i++) {
                pagination.append(`
                    <li class="page-item ${i === currentPage ? 'active' : ''}">
                        <a class="page-link" href="#" onclick="loadPosts(${i})">${i}</a>
                    </li>
                `);
            }

            // 下一页
            pagination.append(`
                <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="loadPosts(${currentPage + 1})">下一页</a>
                </li>
            `);
        }
    </script>
</body>
</html> 